package mt.demo.service.security;

import mt.demo.domain.user.UserDomain;
import mt.demo.service.comm.YomsException;
import mt.demo.service.system.SysFunctionService;
import mt.demo.service.user.RoleService;
import mt.demo.service.user.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayDeque;
import java.util.Collection;

/**
 * Created by watson on 2015/11/12.
 */
@Component
public class WatUserDetailService implements UserDetailsService {
    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private SysFunctionService sysFunctionService;

    //返回当前配置----下面的类是特定的类不能改名字
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
        WatUserDetails details = new WatUserDetails();
        try {

            UserDomain domain = userService.getUserDomainByUserName(userName);
            details.setUsername(domain.getUserLoginName());
            details.setPassword(domain.getUserLoginPassword());
            details.setNickname(domain.getUserNickname());
            details.setUserid(domain.getUserId());
            details.setAvatar(domain.getUserHead());
            details.setRealname(domain.getUserName());
            //必须要有权限
            details.setAuthorities(getAuthority());

        } catch (YomsException e) {
            throw new UsernameNotFoundException("无法查找到用户");
        }
        return details;
    }

    //必须实现权限接口,赋予seritu.xml的默认值ROLE_USER才能获取到权限
    public Collection<GrantedAuthority> getAuthority() throws YomsException {
        Collection<GrantedAuthority> authoritys = new ArrayDeque<>();
        /*//根据用户id获取角色列表
        List<UserRoleDomain> domains = roleService.getAllRoleByuserId(userId);
        //根据角色列表获取所有对应的功能值
        List<SysFunctionDomain> functionDomains = sysFunctionService.getRoleFunction(domains);
        //将功能列表进行遍历的到功能函数属性列表
        for (SysFunctionDomain functionDomain : functionDomains) {
            final String functionNo = functionDomain.getSysFuncNo();
            //将函数列表放入权限列表
            authoritys.add(new WatAuthority(functionNo));
        }*/
        authoritys.add(new WatAuthority("ROLE_USER"));
        return authoritys;
    }

}
